﻿using MMSA.Services.Services;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using SmartProcess.Core.Commons.Tracing;
using MMSA.HttpServices.Properties;

namespace MMSA.HttpServices.Controllers
{
    public class FilesController : ApiController
    {
        #region Properties and Attributes
        TracingService tracingService = new TracingService("MMSA.Services");
        const string DownloadPath = "DirPath";
        const string FileType = "fileType";
        const string OkUploadUrlReturned = "urlResultado";
        const string ErrorUploadUrlReturned = "urlError";
        
        #endregion

        //POST UPLOAD FILES
        [Route("api/uploadfile")]
        public async Task<HttpResponseMessage> PostFormData()
        {
            var traceMessage = string.Empty;

            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                tracingService.ErrorFormat(Resources.ContentNotSupported, Request.Content.Headers.ContentType.MediaType);
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = ConfigurationManager.AppSettings[DownloadPath]; // HttpContext.Current.Server.MapPath("~/App_Data");

            if (string.IsNullOrWhiteSpace(root) || !System.IO.Directory.Exists(root))
            {
                tracingService.Error(Resources.FileDownloadPathNotFound);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, Resources.FileDownloadPathNotFound);
            }

            traceMessage = string.Format(Resources.DowloadFilePathMessage, root);

            tracingService.Verbose(traceMessage);

            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                traceMessage = Resources.StartFileReadingMessage;
                tracingService.Verbose(traceMessage);

                await Request.Content.ReadAsMultipartAsync(provider);

                var filename = provider.FileData[0]
                    .LocalFileName.Replace(root, string.Empty).Replace("\"", string.Empty);

                traceMessage = string.Format(Resources.EndOfFileReadingMessage, filename);

                
                var fileTypes = provider.FormData.GetValues(FileType);
                var fileExtension = provider.FileData[0].Headers.ContentDisposition.FileName.Replace("\"", string.Empty).Split('.')[1].ToString();

                var uploadFileType = string.Empty;

                if (fileExtension.Equals("xls") || fileExtension.Equals("xlsx"))
                {
                        if (fileTypes.Length == 0)
                        {
                            traceMessage = Resources.DefaultFileTypeSelectedMessage;
                            tracingService.Warning(traceMessage);
                        }
                        else
                            uploadFileType = fileTypes[0];

                        var fullFileName = root + filename;
                        traceMessage = string.Format(Resources.StartOfMassiveUploadMessage, uploadFileType, fullFileName);
                        tracingService.Information(traceMessage);
                 
                        var dataManagementService = DataManagementServiceFactory.GetDataManagementService(uploadFileType);
                        // Call to batch upload services
                        dataManagementService.MassiveProductUpload(fullFileName, fileExtension);

                        var response = Request.CreateResponse(HttpStatusCode.Moved);
                        response.Headers.Location = new Uri(ConfigurationManager.AppSettings[OkUploadUrlReturned]);
                        return response;
                }else{
                    
                    var response1 = Request.CreateResponse(HttpStatusCode.Moved);
                    response1.Headers.Location = new Uri(ConfigurationManager.AppSettings[ErrorUploadUrlReturned]);
                    return response1;
                    
                }
            }
            catch (Exception e)
            {
                tracingService.ErrorFormat(Resources.UploadErrorMessage, traceMessage, e.Message, e.StackTrace);
                var response = Request.CreateResponse(HttpStatusCode.Moved);
                response.Headers.Location = new Uri(ConfigurationManager.AppSettings[ErrorUploadUrlReturned]);
                return response;
            }
        }
    }
}
